
<script>
import { getinfos,
  getProductTypeList,
  getTreeDataSelectList,
  getHostList, getInstallTypeList,
  getProgramPath,
  doUpdate, doAdd
} from '@/api/buyoff/TPIRFT'
import Vue from 'vue'
export default {
  name: 'TPIRFTForm',
  data() {
    return {
      dialogVisible: false,
      infoForm: {
        userName: this.$store.state.user.user.userName,
        userID: this.$store.state.user.user.userID,
        // toolingModel: new Date().toJSON().slice(0, 10),
        effectiveTime: new Date().toLocaleDateString().replace(/\//g, '-') + ' ' + new Date().toTimeString().slice(0, 5)
      },
      selectList: {},
      rules: Object.freeze(
        {
          productType: [{ required: true, message: `${this.$t('pleaseSelect')}${this.$t('productType')}`, trigger: 'change' }],
          customCode: [{ required: true, message: `${this.$t('pleaseSelect')}${this.$t('customCode')}`, trigger: 'change' }],
          eqpTypename: [{ required: true, message: `${this.$t('pleaseSelect')}${this.$t('modelName')}`, trigger: 'change' }],
          eqpName: [{ required: true, message: `${this.$t('pleaseSelect')}${this.$t('eqpName')}`, trigger: 'change' }],
          testProgramPath: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('testProgramPath')}`, trigger: 'blur' }],
          effectiveTime: [{ required: true, message: `${this.$t('pleaseSelect')}${this.$t('effectiveTime')}`, trigger: 'change' }],
          objectPath: [{ required: true, message: `${this.$t('pleaseInput')}objectPath`, trigger: 'blur' }]
        }
      )
    }
  },
  computed: {
    isShow: function() {
      if (Array.isArray(this.selectList.productType) && this.selectList.productType.length > 0) {
        return this.selectList.productType.find(ele => ele.name === 'MPG FT').id === this.infoForm.productType
      } else {
        return false
      }
    }
  },
  methods: {
    async setEqpName() {
      const productType = this.selectList.productType.find(ele => ele.id === this.infoForm.productType)
      const eqpTypeName = this.selectList.eqpTypename.find(ele => ele.id === this.infoForm.eqpTypename)
      const res = await getHostList({ productType: productType.name, eqpTypeName: eqpTypeName.name })
      this.$set(this.selectList, 'eqpName', Array.isArray(res.data) ? res.data : [])
    },
    async setLevels() {
      const selectValue = ['eqpTypename', 'levelOne', 'levelTwo', 'levelThree', 'levelFour']
      selectValue.map(async(ele, i) => {
        if (i < 4) {
          const res = await getTreeDataSelectList({ DataId: this.infoForm[selectValue[i]] })
          this.$set(this.selectList, selectValue[i + 1], res.data)
        }
      })
    },
    async handleOpen(row) {
      await this.getProductTypeList()
      if (row && row.id) {
        const res = await getinfos({ id: row.id })
        this.infoForm = Object.assign({}, this.infoForm, res.data)
        // 烦😡
        const values = ['productType', 'customCode', 'eqpTypename']
        await Promise.all(values.map(async(ele, index) => {
          if (this.infoForm.hasOwnProperty(values[index])) {
            if (index === 2) return
            const res = await getTreeDataSelectList({ DataId: this.infoForm[values[index]] })
            this.$set(this.selectList, values[index + 1], res.data)
          }
        }))
        await this.setLevels()
        this.setEqpName()
      }
      await this.getInstallType()
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].$refs['dynForm'].clearValidate()
        this.$refs['formBottom'].$refs['dynForm'].clearValidate()
      })
    },
    handleSave() {
      const dataForm = new Promise((resolve, reject) => {
        this.$refs['dataForm'].$refs['dynForm'].validate((valid) => {
          valid ? resolve(valid) : reject(valid)
        })
      })
      const formBottom = new Promise((resolve, reject) => {
        this.$refs['formBottom'].$refs['dynForm'].validate((valid) => {
          valid ? resolve(valid) : reject(valid)
        })
      })
      Promise.all([dataForm, formBottom]).then(() => {
        if (this.infoForm.id) {
          doUpdate(this.$clearNull(this.infoForm)).then(res => {
            this.$betterTips(res, this.handleClose, this.handleUpdate)
          })
        } else {
          doAdd(this.$clearNull(this.infoForm)).then(res => {
            this.$betterTips(res, this.handleClose, this.handleUpdate)
          })
        }
      }).catch(rej => {
        return false
      })
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    handleUpdate() {
      this.$emit('initList')
    },
    // 获取产品种类数据
    async getProductTypeList() {
      const res = await getProductTypeList()
      this.$set(this.selectList, 'productType', res.data)
    },
    // 获取InstallType
    async getInstallType() {
      const res = await getInstallTypeList({ enumName: 'InstallTypeEnum' })
      this.$set(this.selectList, 'installType', res.data)
    }
  },
  render(h) {
    const searchTagsTop = Vue.observable([
      { label: this.$t('productType'), prop: 'productType', tag: 'DynSelect', event: async(value) => {
        ['customCode', 'eqpTypename', 'eqpName', 'levelOne', 'levelTwo', 'levelThree', 'levelFour'].forEach(ele => {
          this.$set(this.infoForm, ele, '')
          this.$set(this.selectList, ele, [])
        })
        dynShowinput.forEach((ele) => {
          this.$set(this.infoForm, ele.prop, '')
        })
        const res = await getTreeDataSelectList({ DataId: value })
        this.$set(this.selectList, 'customCode', res.data)
      } },
      { label: this.$t('customCode'), prop: 'customCode', tag: 'DynSelect', event: async(value) => {
        ['eqpTypename', 'eqpName', 'levelOne', 'levelTwo', 'levelThree', 'levelFour'].forEach(ele => {
          this.$set(this.infoForm, ele, '')
          this.$set(this.selectList, ele, [])
        })
        const res = await getTreeDataSelectList({ DataId: value })
        this.$set(this.selectList, 'eqpTypename', res.data)
      } },
      { label: this.$t('modelName'), prop: 'eqpTypename', tag: 'DynSelect', event: async(value) => {
        ['eqpName', 'levelOne', 'levelTwo', 'levelThree', 'levelFour'].forEach(ele => {
          this.$set(this.infoForm, ele, '')
          this.$set(this.selectList, ele, [])
        })
        // x_x 绷不住了
        this.setEqpName()
      } },
      { label: this.$t('hostName'), prop: 'eqpName', tag: 'DynSelect', event: async(value) => {
        ['levelOne', 'levelTwo', 'levelThree', 'levelFour'].forEach(ele => {
          this.$set(this.infoForm, ele, '')
          this.$set(this.selectList, ele, [])
        })
        const res = await getTreeDataSelectList({ DataId: this.infoForm.eqpTypename })
        this.$set(this.selectList, 'levelOne', res.data)
      } },
      { label: 'Level1', prop: 'levelOne', tag: 'DynSelect', event: async(value) => {
        ['levelTwo', 'levelThree', 'levelFour'].forEach(ele => {
          this.$set(this.infoForm, ele, '')
          this.$set(this.selectList, ele, [])
        })
        const res = await getTreeDataSelectList({ DataId: value })
        this.$set(this.selectList, 'levelTwo', res.data)
      } },
      { label: 'Level2', prop: 'levelTwo', tag: 'DynSelect', event: async(value) => {
        ['levelThree', 'levelFour'].forEach(ele => {
          this.$set(this.infoForm, ele, '')
          this.$set(this.selectList, ele, [])
        })
        const res = await getTreeDataSelectList({ DataId: value })
        this.$set(this.selectList, 'levelThree', res.data)
      }, vif: () => {
        return this.selectList['levelTwo'] ? this.selectList['levelTwo'].length > 0 : false
      } },
      { label: 'Level3', prop: 'levelThree', tag: 'DynSelect', event: async(value) => {
        ['levelFour'].forEach(ele => {
          this.$set(this.infoForm, ele, '')
          this.$set(this.selectList, ele, [])
        })
        const res = await getTreeDataSelectList({ DataId: value })
        this.$set(this.selectList, 'levelFour', res.data)
      }, vif: () => {
        return this.selectList['levelThree'] ? this.selectList['levelThree'].length > 0 : false
      } },
      { label: 'Level4', prop: 'levelFour', tag: 'DynSelect', vif: () => {
        return this.selectList['levelFour'] ? this.selectList['levelFour'].length > 0 : false
      } },
      { label: 'Install Type', prop: 'installType', tag: 'DynSelect' },
      { label: 'Test Program Path', prop: 'testProgramPath', tag: 'DynInput', width: '100%', className: 'long-width',
        handlerEnter: async(e) => {
          const { productType, customCode, eqpTypename, eqpName, installType, levelOne,
            levelTwo, levelThree, levelFour
          } = this.infoForm
          const res = await getProgramPath(this.$clearNull({ productType, customCode, eqpTypename, eqpName, installType, levelOne,
            levelTwo, levelThree, levelFour
          }))
          if (res.code === 1) {
            this.$set(this.infoForm, 'testProgramPath', res.data)
            e.target.blur()
          }
        }
      },
      { label: 'Install Test Program(except *.pro) to ECN and SWR Directory',
        width: '100%', prop: 'installProgramYesno', tag: 'DynSwitch', labelWidth: '450px' },
      { label: 'Remove calibration files from server(t5592 & t5593 only)',
        width: '100%', prop: 'removeFilesYesno', tag: 'DynSwitch', labelWidth: '450px' }
    ])
    const dynShowinput = [
      { label: 'Spec No', prop: 'specNumber', tag: 'DynInput', vif: () => {
        return this.isShow
      } },
      { label: 'Spec Version', prop: 'specVersion', tag: 'DynInput', vif: () => {
        return this.isShow
      } }
    ]
    const searchTagsBtn = [
      { label: 'Object Path', prop: 'objectPath', tag: 'DynInput' },
      { label: 'Remark', prop: 'remark', tag: 'DynInput' },
      { label: 'Effective Time', prop: 'effectiveTime', tag: 'Dyndate',
        datatype: 'datetime', dataformat: 'yyyy-MM-dd HH:mm' },
      { label: 'Remove', prop: 'removeYesno', tag: 'DynSwitch' }
    ]
    return (
      <el-dialog
        visible={this.dialogVisible} {...{ on: 'update:visible' }}
        before-close={this.handleClose}
        close-on-click-modal={false}
        title='TPIR-FT'
        width='80%'>
        <div class='base-info'>
          <el-form inline={true} label-width='130px'>
            <el-form-item label={`${this.$t('employeeName')}:`}>
              <span>{ this.infoForm.userName }</span>
            </el-form-item>
            <el-form-item label={`${this.$t('employeeID')}:`}>
              <span>{ this.infoForm.userID }</span>
            </el-form-item>
            <el-form-item label='Version:'>
              <span>{ this.infoForm.toolingBarcode }</span>
            </el-form-item>
            <el-form-item label={`${this.$t('writeFormDate')}:`}>
              <span>{ new Date().toJSON().slice(0, 10) }</span>
            </el-form-item>
          </el-form>
        </div>
        <div class='line' style='width: 100%; border: 1px solid #F5F5F5; marginBottom: 10px'/>
        <div class='form-box'>
          <dynForm info-form={this.infoForm}
            selectList={this.selectList}
            rules={this.rules}
            ref='dataForm'
            search-tags={searchTagsTop} label-width='150px'/>
          <div class='line' style='width: 100%; border: 1px solid #F5F5F5; marginBottom: 10px'/>
          <dynForm
            ref='formBottom'
            info-form={this.infoForm}
            rules={this.rules}
            search-tags={[...dynShowinput, ...searchTagsBtn]} label-width='140px'/>

        </div>
        <span slot='footer'>
          <el-button size='small' icon='el-icon-circle-close' on-click={this.handleClose}>
            {this.$t('cancel')}</el-button>
          <el-button size='small' type='primary' icon='el-icon-receiving' on-click={this.handleSave}>
            {this.$t('save')}</el-button>
        </span>
      </el-dialog>
    )
  }
}
</script>
<style scoped lang="scss">
  ::v-deep .el-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    .el-form-item {
      width: 30%;
      .el-form-item__content .el-date-editor{
          width: 175px;
      }
    }
      .long-width {
        .el-form-item__content{
          width: 60%;
        }
      }
  }
</style>
